<?php

namespace App\Http\Controllers\Api\Backstage;

use App\Models\Commodity;
use App\Models\Science;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class ScienceController extends Controller
{
    public function index()
    {
        $data['scienceList'] = Science::select('t1.*','t2.commodityName')
        ->from((new Science())->getTable().' as t1')
        ->leftJoin((new Commodity())->getTable().' as t2','t1.commodityId','=','t2.commodityId')
        ->get();
        return $this->apiResponse($data);
    }

    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'scienceId' => 'integer|required',
            'caption' => 'required',
            'content' => 'required',
            'bgPicture' => 'required',
            'smallPicture' => 'required',
            'commodityId' => 'integer'
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }

        $scienceId = @$data['scienceId'];
        unset($data['scienceId']);
        $status = Science::where('scienceId', $scienceId)->update($data);

        if (!$status) {
            return $this->apiResponse('', config('errorCode.EDI_REQ_FAILED'));
        }else{
            return $this->apiResponse(true);
        }
    }

    public function update(Request $request, $scienceId)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'commodityId' => 'required|integer'
        ]);
        if ($validator->fails()) {
            return $this->apiResponse('', config('errorCode.INVALID_REQ_PARAMS'));
        }
        $status = Science::where('scienceId', $scienceId)->update($data);
        if (!$status) {
            return $this->apiResponse('', config('errorCode.EDI_REQ_FAILED'));
        }else{
            return $this->apiResponse(true);
        }
    }

    public function show($scienceId)
    {
        $data = Science::find($scienceId);
        return $this->apiResponse($data);
    }


}
